import { createRouter, createWebHistory } from "vue-router";

import { getToken } from "@/utils/auth";
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";

export const routes = [
	{ path: '/login', name: 'Login', component: () => import('@/views/Login.vue'), meta: { requiresAuth: false } },
    { 
        path: '/', 
        name: 'Home', 
        component: () => import('@/views/Home.vue'), 
        meta: { requiresAuth: true },
        redirect: '/pets/archive',
        children: [
            { path: 'pets/archive', name: 'Archive', component: () => import('@/views/pets/Archive.vue'), meta: { requiresAuth: true } },
            { path: 'settings/user', name: 'User', component: () => import('@/views/settings/User.vue'), meta: { requiresAuth: true } },
            { path: 'pets/weight', name: 'Weight', component: () => import('@/views/pets/Weight.vue'), meta: { requiresAuth: true } },
            { path: '/health/disease', name: 'Disease',component: () => import('@/views/healths/Disease.vue'), meta: { requiresAuth: true } }
        ]
    },
]

const router = createRouter({
	history: createWebHistory(),
	routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = getToken();

  // 默认需要登录，除非显式标注 requiresAuth: false
  const needAuth = to.meta.requiresAuth !== false;

  if (needAuth && !token) {
    // 未登录，跳去登录并带上原目标地址
    next({ name: 'Login', query: { redirect: to.fullPath } });
  } else if (to.name === 'Login' && token) {
    // 已登录访问登录页 -> 送回首页
    next({ name: 'Home' });
  } else {
    next();
  }
});

export default router;